package com.starling.control
{
	import com.starling.control.file.FileBase;
	import com.starling.control.file.FileDIR;
	import com.starling.control.file.FilePSD;
	import com.starling.control.file.FileSWF;
	import com.starling.utils.TextureUtil;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.PNGEncoderOptions;
	import flash.events.Event;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.net.FileFilter;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;
	
	public class MainControl
	{
		protected const fileFilter:FileFilter = new FileFilter("选择文件","*.swf;*.psd");
		
		private var _file:FileBase;
		
		public function MainControl()
		{
			
		}
		
		
		
		
		/** JSFL处理 */		
		public function onJSFL():void
		{
			var file:File = File.applicationDirectory.resolvePath("SetClassName.jsfl");
			file.openWithDefaultApplication();
		}
		
		
		
		
		
		/** 打开当前目录 */		
		public function openDIR():void
		{
			try{
				if(_file.isDirectory)
				{
					_file.openWithDefaultApplication();
				}else{
					_file.parent.openWithDefaultApplication();
				}
			}catch(e:Error){
				trace(e.message);
			}
		}
		
		
		
		/** 选择文件或目录 */		
		public function select(type:String):void
		{
			var f:File = new File();
			if(type==FileBase.DIR)
			{
				f.browseForDirectory("选择图片文件夹");
			}else{
				f.browse([fileFilter]);
			}
			f.addEventListener(Event.SELECT,function():void
			{
				selectComplete(f);
			});
		}
		
		
		
		
		/**
		 * 文件选择完成 
		 * @param f
		 * 
		 */		
		private function selectComplete(f:File):void
		{
			if(_file!=null)
			{
				_file.dispose();
				_file = null;
			}
			
			switch(f.extension)
			{
				case "swf":		_file = new FileSWF(f.nativePath);	break;
				case "psd":		_file = new FilePSD(f.nativePath);	break;
				case null:		_file = new FileDIR(f.nativePath);	break;
			}
			
			onUpdate();
		}
		
		
		/** 更新文件 */
		public function onUpdate():void
		{
			Manage.mainView.mouseChildren = false;
			Manage.mainView.text_file_info.text = "";
			_file.loadFile(loadComplete);
		}
		
		
		/** 文件加载完成  */	
		private function loadComplete():void
		{
			Manage.mainView.mouseChildren = true;
			Manage.mainView.button_open_dir.enabled = true;
			Manage.mainView.button_update.enabled = true;
			Manage.mainView.button_publish.enabled = true;
			
			Manage.mainView.text_file_path.text = decodeURI(_file.nativePath);
			
			/** 排序处理 */
			_file.fileItems.sort(function (a:Object,b:Object):int
			{
				var type1:String = a.textureType;
				var type2:String = b.textureType;
				return type1 == type2 ? 1 : -1;
				//return type1.length<type2.length ? -1 : 1;
			});
			
			var info:String = "";
			if(_file.fileType==FileBase.DIR)
			{
				info += "\n------------------------目录信息------------------------";
				info += "\n\n目录名：" + _file.name;
				info += "\n\n包含图片数量：" + _file.fileNum;
				info += "\n\n包含图片总大小：" + (_file.fileSize/1024/1024).toFixed(2) + " MB";
			}else{
				info += "\n------------------------文件信息------------------------";
				info += "\n\n文件名：" + _file.name;
				info += "\n\n文件大小：" + (_file.fileSize/1024/1024).toFixed(2) + " MB";
			}
			info += "\n\n最后修改时间：" + _file.fileUpdate;
			
			info += "\n\n------------------------资源信息------------------------";
			for (var i:int=0;i<_file.fileItems.length;i++)
			{
				var type:String = _file.fileItems[i].textureType;
				if(type!=null)
				{
					var gap:String = type.length>2?"   ":"    ";
					info += "\n类型：" + type + gap + "资源名：" + _file.fileItems[i].textureName;
				}
			}
			
			Manage.mainView.text_file_info.text = info;
			Manage.mainView.text_file_info.textField.scrollV = 0;
		}
		
		
		
		
		
		
		/**
		 * 发布
		 * 
		 */
		
		public function onPublish():void
		{
			Manage.mainView.text_file_info.text = "\n发布中...\n"+Manage.mainView.text_file_info.text;
			Manage.mainView.text_file_info.textField.scrollV = 0;
			Manage.mainView.mouseChildren = false;
			setTimeout(publishHandler ,50);
		}
		
		
		
		/** 发布处理 */
		private function publishHandler():void
		{
			try{
				/** 创建显示对象数据 */
				var obj:Object = _file.getInfo(Number(Manage.mainView.input_scale.text));
				if(obj!=null)saveBytes(obj ,_file.savePath+_file.fileName+".bytes");
				createTextureFile();
				
				Manage.mainView.text_file_info.text = "\n"+BDate.formatDate(new Date())+"   发布成功...\n"+Manage.mainView.text_file_info.text;;
			}catch(e:Error){
				Manage.mainView.text_file_info.text = "\n发布失败..."+e.message+"\n"+Manage.mainView.text_file_info.text;;
			}
			
			Manage.mainView.mouseChildren = true;
		}
		
		
		/** 创建纹理及XML文件 */
		private function createTextureFile():void
		{
			var bigWidth:int = Number(Manage.mainView.input_width.text);
			var bigHeight:int = Number(Manage.mainView.input_height.text);
			var padding:int = Number(Manage.mainView.input_padding.text);
			var match:Boolean = Manage.mainView.check_match.selected;
			
			var dataItems:Array = [];
			var rectMaps:Object = {};
			
			for (var i:int=0;i<_file.fileItems.length;i++)
			{
				if(_file.fileItems[i].textureType==TextureUtil.TYPE_IMAGE
					|| _file.fileItems[i].textureType==TextureUtil.TYPE_SCALE9GRID)
				{
					var bitmapData:BitmapData;
					if(_file.fileType==FileBase.PSD)
					{
						bitmapData = _file.fileItems[i].display.bitmapData;
					}else{
						bitmapData = TextureUtil.getDisplayBitmapdata(_file.fileItems[i].display);
					}
					
					
					var big:Boolean = false;
					if(match)
					{
						if(bitmapData.width>=bigWidth && bitmapData.height>=bigHeight)big=true;
					}else{
						if(bitmapData.width>=bigWidth || bitmapData.height>=bigHeight)big=true;
					}
					
					if(big)
					{
						saveImage(bitmapData ,_file.savePath+"Big/"+_file.fileItems[i].textureName+".png");
					}else{
						rectMaps[_file.fileItems[i].textureName] = new Rectangle(0 ,0 ,bitmapData.width ,bitmapData.height);
						dataItems.push({bitmapData:bitmapData ,textureName:_file.fileItems[i].textureName});
					}
				}
			}
			
			
			var textureAtlasRect:Rectangle = TextureUtil.packTextures(0 ,padding ,rectMaps);
			if(textureAtlasRect)
			{
				var textureAtlasBitmapData:BitmapData = new BitmapData(textureAtlasRect.width,textureAtlasRect.height,true,0);
				var xml:XML = <TextureAtlas />;
				xml.@imagePath = _file.fileName+".png";
				
				var childXml:XML;
				var textureName:String;
				var tempRect:Rectangle = new Rectangle();
				var tempPoint:Point = new Point();
				
				for (var j:int=0; j< dataItems.length; j++) 
				{
					textureName = dataItems[j].textureName;
					tempRect.width = dataItems[j].bitmapData.width;
					tempRect.height = dataItems[j].bitmapData.height;
					tempPoint.x = rectMaps[textureName].x;
					tempPoint.y = rectMaps[textureName].y;
					
					childXml = <SubTexture />;
					childXml.@name = textureName;
					childXml.@x = tempPoint.x;
					childXml.@y = tempPoint.y;
					childXml.@width = tempRect.width;
					childXml.@height = tempRect.height;
					xml.appendChild(childXml);
					
					textureAtlasBitmapData.copyPixels(dataItems[j].bitmapData ,tempRect,tempPoint);
				}
				
				saveImage(textureAtlasBitmapData ,_file.savePath+_file.fileName+".png");
				saveXML(xml ,_file.savePath+_file.fileName+".xml");
			}
		}
		
		
		
		
		
		
		
		
		
		/**
		 * 写入Bitmap
		 * @param bitmapdata
		 * 
		 */		
		private function saveImage(bitmapdata:BitmapData ,path:String):void
		{
			var bytes:ByteArray = bitmapdata.encode(new Rectangle(0 ,0 ,bitmapdata.width,bitmapdata.height) ,new PNGEncoderOptions());
			var file:File = new File(path);
			var fs:FileStream = new FileStream();
			fs.open(file,FileMode.WRITE);
			fs.writeBytes(bytes);
			fs.close();
		}
		
		/**
		 * 写入XML
		 * 
		 */		
		private function saveXML(data:String ,path:String):void
		{
			var bytes:ByteArray = new ByteArray();
			bytes.writeMultiByte(data,"utf-8");
			var file:File = new File(path);
			var fs:FileStream = new FileStream();
			fs.open(file,FileMode.WRITE);
			fs.writeBytes(bytes);
			fs.close();
		}
		
		
		
		/**
		 * 写入Bytes
		 * 
		 */		
		private function saveBytes(data:Object ,path:String):void
		{
			var butes:ByteArray = new ByteArray();
			butes.writeMultiByte(JSON.stringify(data),"utf-8");
			butes.compress();
			var file:File = new File(path);
			var fs:FileStream = new FileStream();
			fs.open(file,FileMode.WRITE);
			fs.writeBytes(butes);
			fs.close();
		}
	}
}